package com.sunrise.gateway.web.core;

import com.dap.commons.Constants;
import com.dap.exception.BusinessException;
import com.dap.exception.PlatformException;
import com.dap.param.ImportParam;
import com.dap.param.StringInput;
import com.sunrise.gateway.FrontendVersionManagerBase;
import com.sunrise.gateway.commons.CommonUtils;
import com.dap.utils.ExcelUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/****
 * 导出excel请求转发核心功能
 * @author wangmin
 */
@Service
public class ImportEngine extends EngineBase {
    private final static Logger LOGGER = LoggerFactory.getLogger(ImportEngine.class);

    private ServletFileUpload upload;

    public ImportEngine() {
        super();

        DiskFileItemFactory factory = new DiskFileItemFactory();
        upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
    }


    public String execute(HttpServletRequest req) {
        String group = CommonUtils.getGroup(req);

        // 获取参数 - 起始行, 从0开始
        int startRow = 1;
        String startRowStr = req.getParameter("startRow");
        if (!StringUtils.isEmpty(startRowStr)) {
            try {
                startRow = Integer.parseInt(startRowStr);
            } catch (Exception e) {
            }
        }

        // 获取参数 - 起始列, 从0开始
        int startCol = 0;
        String startColStr = req.getParameter("startCol");
        if (!StringUtils.isEmpty(startColStr)) {
            try {
                startCol = Integer.parseInt(startColStr);
            } catch (Exception e) {
            }
        }

        // 获取参数 - 是否多个sheet, 默认为false
        boolean hasMultiSheet = "true".equalsIgnoreCase(req.getParameter("hasMultiSheet"));


        // 读取并解析excel
        Object content = null;
        try {
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    InputStream inputStream = item.getInputStream();

                    // 获取后缀
                    String extension = Constants.EXCEL_EXTENSION_XLS;
                    String itemName = item.getName();
                    if (!StringUtils.isEmpty(itemName)) {
                        int extensionIdx = itemName.lastIndexOf('.');
                        if (extensionIdx >= 0) {
                            extension = itemName.substring(extensionIdx);
                        }
                    }

                    if (hasMultiSheet) {
                        content = ExcelUtils.readMultiSheetExcelContent(
                                inputStream, Integer.MAX_VALUE, startRow, startCol, extension);
                    } else {
                        content = ExcelUtils.readSingleSheetExcelContent(inputStream, startRow, startCol, extension);
                    }

                    item.delete();

                    break;
                }
            }
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.warn("", e);
            throw new PlatformException(Constants.ResponseCode.FILE_UPLOAD_FAILURE);
        }
        if (null == content) {
            throw new PlatformException(Constants.ResponseCode.FILE_UPLOAD_FAILURE);
        }

        // 获取额外参数
        Map<String, String> extraParam = new HashMap<>();
        Enumeration pn = req.getParameterNames();
        while (pn.hasMoreElements()) {
            String parameterName = (String) pn.nextElement();
            String value = req.getParameter(parameterName);
            extraParam.put(parameterName, value);
        }

        ImportParam importParam = new ImportParam(content, extraParam);
        StringInput input = new StringInput(importParam);

        return execute(req, group, input);
    }

    private String execute(HttpServletRequest req, String group, StringInput input) {
        // 前端版本更新, 请求无效
        FrontendVersionManagerBase.checkFrontendVersion(req, input);

        // ctrlData添加基本信息
        fillSessionInfoIntoCtrlDataInterface.fill(input, group, req);

        return executeRequestStr(group, input, true);
    }
}
